package cn.nsu.douban.web.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.StringCharacterIterator;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.http.auth.NTCredentials;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;
import org.h2.constant.SysProperties;
import org.joda.time.field.OffsetDateTimeField;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.alibaba.fastjson.JSONObject;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.config.entities.ActionConfig;

import cn.nsu.douban.entity.ActorInfo;
import cn.nsu.douban.entity.MovieInfo;
import cn.nsu.douban.entity.User;
import cn.nsu.douban.service.IActorService;
import cn.nsu.douban.service.IMovieService;
import cn.nsu.douban.service.IUserService;
import cn.nsu.douban.service.impl.IUserServiceImpl;
import cn.nsu.utils.HttpClientUtil;

@SuppressWarnings("all")
@Controller
@Scope("prototype")
public class UserAction extends ActionSupport /*implements SessionAware */{
  
	//上传
		public File file;
		public String fileFileName;
	    public  String  fileContentType;	
		
	
	 //手机号
	public String phone;
	
	public  MovieInfo  mi=new MovieInfo();
	//用户ID
	public Integer  userid;
	
	public static String VIEW_LOGIN = "loginpage";
	public static String VIEW_REGISTER = "registerpage";
    public static Integer pageSize=4;
    public Integer pageNum=0;
    public  Integer   totlPage;
    private Map mySession;
	//自动登录
    public Integer remember=0;
    
    @Resource
    private IActorService iActorService;
    
	// 属性驱动
	public User user = new User();
	// 检查重复名
	public String loginname;

	@Resource
	private IUserService iuserService;
	@Resource
	private IMovieService imovieService;
	//sessionID URL传参
	public String sessionid;

	// 注册页
	public String registerForm() {
		return VIEW_REGISTER;
	}
	
	static String imageRootPat="http://localhost:8080/dy/";
	public String save() throws IOException{
      ActorInfo actorInfo=new ActorInfo();
      actorInfo.setId(userid);
		mi.setDate(new Date());
		HashSet<ActorInfo> acList=new HashSet<ActorInfo>();
		acList.add(actorInfo);
		mi.setAc(acList);
		String fileType = fileFileName.substring(fileFileName.lastIndexOf("."));
		String fileName = UUID.randomUUID().toString().replace("-", "");
		String newFileName=fileName+fileType;
		String path="E:\\xuni\\"+newFileName;
		File files=new File(path);
		FileUtils.copyFile(file, files);
		mi.setImagpath("http://localhost:8080/dy/"+newFileName);
		imovieService.save(mi);
		return "to_adminMain";
	}

	
	//添加页
	public String addPage(){
		  List<ActorInfo> amList=iActorService.getAll();
		  System.out.println(amList.size());
		  ServletActionContext.getContext().getValueStack().set("aList", amList);
		return "addPage";
	}

	// 登陆页
	public String loginPage() {
		return VIEW_LOGIN;
	}

	
	//手机验证码
	public void getPhoeCode() throws IOException{
		//用户名
		String Uid = "a6165164";
		//接口安全秘钥
		String Key = "2cc9a742d22947bd917d";
		HttpClientUtil client = HttpClientUtil.getInstance();
		 String smsMob = phone;
			//短信内容
		 Random random=new Random(1);
		int first=Math.abs(random.nextInt(10));
		int second=Math.abs(random.nextInt(10));
		int three=Math.abs(random.nextInt(10));
		int four=Math.abs(random.nextInt(10));
        String smsText = ""+first+second+three+four;
        //保存验证码
		ServletActionContext.getRequest().getSession().setAttribute("code",Integer.parseInt(smsText));
		//UTF发送
		int result = client.sendMsgUtf8(Uid, Key, smsText, smsMob);
		if(result>0){
			System.out.println("UTF8成功发送条数=="+result);
		}else{
			System.out.println(client.getErrorMsg(result));
		}
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		 PrintWriter writer = ServletActionContext.getResponse().getWriter();
		 writer.println(smsText);
		 writer.flush();
		 writer.close();
	}
	
	
	// 检查用户名
	public void checkUserName() throws IOException {
		PrintWriter writer = ServletActionContext.getResponse().getWriter();
		ServletActionContext.getResponse().setContentType("application/json;charset=utf-8");
		Integer len = iuserService.findUsername(loginname);
		if (len != 0) {
			writer.print(1);
		} else {
			writer.print(0);
		}
	}

	// 注册
	public String register() {
		try {
			iuserService.register(user);
		} catch (Exception e) {
			e.printStackTrace();
			return registerForm();
		}
		return VIEW_LOGIN;
	}
	// 登陆
	public String login() {
		User temp = iuserService.login(user.getLoginname(), user.getPassword());
	     //管理员登陆
		if(user.getLoginname().equals("admin")&&user.getPassword().equals("admin")){
			ServletActionContext.getRequest().getSession().setAttribute("admin", user);
		    List<MovieInfo>	movieInfos=imovieService.getAll();
	        ActionContext.getContext().put("mList", movieInfos);
			return "adminMain";
		}
		//其余登陆
  		if (temp != null) {
  		    ServletActionContext.getRequest().getSession().setAttribute("USER", temp);
			//加载页面电影准备数据
  			totlPage=imovieService.getMoveiIsHotCount();
			List<MovieInfo> miList=imovieService.getAll(pageNum,pageSize);
          ActionContext.getContext().getValueStack().set("mList", miList);
		/*	return "to_moveishotList";*/
          return "to_moveishotList";
	    	}
		return VIEW_LOGIN;
	}
	//退出
	public String exit(){
	ServletActionContext.getRequest().getSession().setAttribute("USER", null);
	 return VIEW_LOGIN;
	}

	public void setIuserService(IUserService iuserService) {
		this.iuserService = iuserService;
	}
	public void setImovieService(IMovieService imovieService) {
		this.imovieService = imovieService;
	}
	
	public Integer getTotlPage() {
		return totlPage;
	}


	public String getSessionid() {
	 
		return sessionid;
	}

	public void setSessionid(String sessionid) {
		this.sessionid = sessionid;
	}



}
